import React, { useState, useEffect } from 'react';
import type { ResumeData } from '../types';

const initialData: ResumeData = {
  basicInfo: { name: '', email: '', phone: '' },
  education: { school: '', major: '', degree: '', startDate: '', endDate: '' },
};

export const ResumeForm: React.FC = () => {
  const [resumeData, setResumeData] = useState<ResumeData>(initialData);

  // 1. 加载已保存的数据
  useEffect(() => {
    chrome.storage.local.get('resumeData', (result) => {
      if (result.resumeData) {
        setResumeData(result.resumeData);
      }
    });
  }, []);

  // 2. 处理表单输入变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    const [section, field] = name.split('.'); // e.g., name="basicInfo.name"

    setResumeData(prev => ({
      ...prev,
      [section]: {
        ...prev[section as keyof ResumeData],
        [field]: value
      }
    }));
  };

  // 3. 一键填写当前页面
  const handleFill = () => {
    // 查询当前活动的标签页
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0] && tabs[0].id) {
        // 向该标签页发送"开始填写"的指令
        chrome.tabs.sendMessage(tabs[0].id, { action: 'fillForm' }, (response) => {
          if (chrome.runtime.lastError) {
            // 如果发送失败（例如，页面还没加载完），可以给个提示
            console.error(chrome.runtime.lastError.message);
            alert('无法连接到页面，请刷新页面后重试。');
          } else {
            console.log(response.status);
          }
        });
      }
    });
  };

  // 4. 保存数据
  const handleSave = () => {
    chrome.storage.local.set({ resumeData }, () => {
      console.log('简历数据已保存！');
      alert('保存成功！');
    });
  };

  return (
    <div>
      <h3>基本信息</h3>
      <input name="basicInfo.name" value={resumeData.basicInfo.name} onChange={handleChange} placeholder="姓名" />
      <input name="basicInfo.email" value={resumeData.basicInfo.email} onChange={handleChange} placeholder="邮箱" />
      <input name="basicInfo.phone" value={resumeData.basicInfo.phone} onChange={handleChange} placeholder="电话" />
      
      <h3>教育背景</h3>
      <input name="education.school" value={resumeData.education.school} onChange={handleChange} placeholder="学校" />
      <input name="education.major" value={resumeData.education.major} onChange={handleChange} placeholder="专业" />
      <input name="education.degree" value={resumeData.education.degree} onChange={handleChange} placeholder="学位 (如: 本科/硕士)" />
      <input name="education.startDate" value={resumeData.education.startDate} onChange={handleChange} placeholder="开始日期 (YYYY-MM)" />
      <input name="education.endDate" value={resumeData.education.endDate} onChange={handleChange} placeholder="结束日期 (YYYY-MM)" />
      
      <button onClick={handleFill} style={{ backgroundColor: '#28a745', marginBottom: '10px' }}>
        一键填写当前页面
      </button>
      <button onClick={handleSave}>保存简历</button>
    </div>
  );
};
